package com.example.yan_music.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.example.yan_music.app.XApplication;
import com.example.yan_music.event.PlayCompleteEvent;
import com.example.yan_music.event.PlayErrorEvent;
import com.example.yan_music.event.SongIsPreparedEvent;
import com.example.yan_music.utils.XToast;

import org.greenrobot.eventbus.EventBus;

/**
 * <p>
 *      播放服务
 * </p>
 */
public class PlayerService extends Service {

    private static final String TAG = "PlayerService";

    /**
     * 播放器
     */
    private MediaPlayer mMediaPlayer;

    public PlayerService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new PlayBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mMediaPlayer = new MediaPlayer();
    }

    @Override
    public void onDestroy() {
        // 释放资源
        mMediaPlayer.release();
        super.onDestroy();
    }


    /**
     * 通信类
     * <p>
     *     包含对歌曲的操作
     * </p>
     */
    public class PlayBinder extends Binder{

        // 是否在播放
        private boolean isPlaying = false;

        // 设置播放状态
        public void setPlaying(boolean playing) {
            isPlaying = playing;
        }

        /**
         * 播放器恢复到初始状态
         */
        public void reset(){
            mMediaPlayer.reset();
        }

        public boolean isPlaying(){
           return isPlaying;
        }


        public void play(){
            mMediaPlayer.start();
        }

        public void pause(){
            mMediaPlayer.pause();
        }

        /**
         * 播放搜索到的歌曲
         * @param songUrl     歌曲的播放url
         */
        public void playSong(String songUrl){
            try{
                // 让MediaPlayer处于空闲状态
                mMediaPlayer.reset();
                mMediaPlayer.setDataSource(XApplication.getContext(), Uri.parse(songUrl));
                mMediaPlayer.prepare();
                mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        isPlaying = true;
                        // 准备完成时开始播放
                        mp.start();
                        EventBus.getDefault().post(new SongIsPreparedEvent());
                    }
                });

                // 设置播放错误监听，解决点击几次子项播放时SeekBar更新线程中断。原因是发送（-38， 0 ）错误，而OnComplete接口不为空，onError返回false导致
                // 这里就让错误监听返回true即可解决
                mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                    @Override
                    public boolean onError(MediaPlayer mp, int what, int extra) {
                        Log.d(TAG, "onError: " + what);
                        return true;
                    }
                });

                mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        Log.d(TAG, "歌曲播放结束");
                        // 一首歌播放结束后要将SeekBar进度这是成0
                        EventBus.getDefault().post(new PlayCompleteEvent());
                    }
                });
            }catch (Exception e){
                e.printStackTrace();
                EventBus.getDefault().post(new PlayErrorEvent());
                XToast.showError("播放失败");
            }
        }

        /**
         * 返回歌曲的长度
         */
        public int getDuration(){
           return mMediaPlayer.getDuration();
        }

        /**
         * 返回歌曲当前的进度
         */
        public int getCurrentPosition(){
            if(isPlaying){
                //Log.d(TAG, "SeekBarThread线程调用getCurrentPosition: " + mMediaPlayer.getCurrentPosition());
                return mMediaPlayer.getCurrentPosition();
            }else {
                return 0;
            }
        }

        /**
         * 设置歌曲播放进度
         * @param mesc 当前进度
         */
        public void seekTo(int mesc){
            mMediaPlayer.seekTo(mesc);
            Log.d(TAG, "seekTo: ");
        }
    }
}
